<?php

class AppuntamentoController extends Controller {
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array('accessControl',  // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array( array('allow', // allow all users to perform 'index' and 'view' actions
		'actions' => array('calendario', 'view', 'create', 'admin', 'suggestTrattamento', 
		'validate', 'ajaxCreate','edit','ajaxEdit','ajaxDelete'), 'users' => array('*'), ), array('deny', // deny all users
		'users' => array('*'), ), );
	}

	/**
	 * Ritorna un JSON con gli appuntamenti: le loro durate
	 * il nome del cliente, l'orario (senza data) e il trattamento
	 */
	public function actionCalendario($operatore = 0, $giorno = 0, $mese = 0, $anno = 0) {
		if ($operatore == "")
			$operatore = 0;
		if ($giorno == "")
			$giorno = 0;
		if ($mese == "")
			$mese = 0;
		if ($anno == "")
			$anno = 0;

		// Prendo i dati dal DB
		$connection = Yii::app() -> db;

		$command = $connection -> createCommand("SELECT Appuntamenti.id as idAppuntamento, Appuntamenti.data as dataT, Trattamenti.nome as nomeT, Trattamenti.durata as durataT, 
		Clienti.nome as nomeC, Clienti.cognome as cognomeC FROM Appuntamenti
		INNER JOIN Trattamenti
		ON Trattamenti.id = Appuntamenti.trattamento
		INNER JOIN Clienti
		ON Clienti.id = Appuntamenti.cliente
		WHERE Appuntamenti.operatore = " . $operatore . " AND Appuntamenti.data BETWEEN \"" . $anno . "-" . $mese . "-" . $giorno . " 00:00:00\" AND \"" . $anno . "-" . $mese . "-" . $giorno . " 23:59:59\"");

		$dataReader = $command -> query();

		$risultati = array();
		foreach ($dataReader as $row) {
			$cliente = $row['nomeC'] . " " . $row['cognomeC'];
			$trattamento = $row['nomeT'];
			$durata = $row['durataT'];
			$data = $row['dataT'];
			$time = date("F j, Y G:i:s", strtotime($data));

			array_push($risultati, array('cliente' => $cliente, 'trattamento' => $trattamento, 'durata' => $durata, 'data' => $time, 'idAppuntamento' => $row['idAppuntamento']));
		}

		echo CJSON::encode($risultati);

		Yii::app() -> end();
	}

	/**
	 * Create appuntamento
	 */
	public function actionAjaxCreate($operatore, $trattamenti, $giorno, $mese, $anno, $cliente, $ora) {
		$corrispondenze = array("80" => "08:00", "815" => "08:15", "830" => "08:30", "845" => "08:45", "90" => "09:00", "915" => "09:15", "930" => "09:30", 
		"945" => "09:45", "100" => "10:00", "1015" => "10:15", "1030" => "10:30", "1045" => "10:45", "110" => "11:00", "1115" => "11:15", "1130" => "11:30", 
		"1145" => "11:45", "120" => "12:00", "1215" => "12:15", "1230" => "12:30", "1245" => "12:45", "130" => "13:00", "1315" => "13:15", "1330" => "13:30", 
		"1345" => "13:45", "140" => "14:00", "1415" => "14:15", "1430" => "14:30", "1445" => "14:45", "150" => "15:00", "1515" => "15:15", "1530" => "15:30", 
		"1545" => "15:45", "160" => "16:00", "1615" => "16:15", "1630" => "16:30", "1645" => "16:45", "170" => "17:00", "1715" => "17:15", "1730" => "17:30", 
		"1745" => "17:45", "180" => "18:00", "1815" => "18:15", "1830" => "18:30", "1845" => "18:45", "190" => "19:00", "1915" => "19:15", "1930" => "19:30", "1945" => "19:45");
		//$ora = $corrispondenze[$ora].":00";
		
		$trattamentiIds = explode("_", $trattamenti);
		$operatoriIds = explode("_", $operatore);
		$giornoIds = explode("_",$giorno);
		$meseIds = explode("_",$mese);
		$annoIds = explode("_",$anno);
		$oraIds = explode("_",$ora);

		//$step = 0;
		for( $app = 0; $app < count($trattamentiIds); $app++) {
			if ($trattamentiIds[$app]=='') break;
			
			//$trattamento = Trattamento::model()->findByPk($trattamentiIds[$app]);
			//$durata = $trattamento->durata;
			//$chiavi = array_keys($corrispondenze);
			//$chiave = $chiavi[array_search($ora, $chiavi) + $step];
			
			$orario = $corrispondenze[$oraIds[$app]];
			//$step += $durata/15;
			
			$model = new Appuntamento;
			$model->cliente = $cliente;
			$model->trattamento = $trattamentiIds[$app];
			$model->operatore = $operatoriIds[$app];
			$model->data = $annoIds[$app].'-'.$meseIds[$app].'-'.$giornoIds[$app].' '.$orario;
			$model -> save();
		}
		
		echo CJSON::encode("aggiorna");
		
		Yii::app() -> end();
	}
	
	public function actionAjaxDelete($id) {
		$model = Appuntamento::model()->findByPk($id);
		$model -> delete();
		echo CJSON::encode("aggiorna");
		
		Yii::app() -> end();
	}
	
	/**
	 * Edit appuntamento
	 */
	public function actionAjaxEdit($id, $operatore, $trattamento, $giorno, $mese, $anno, $cliente, $ora) {
		$corrispondenze = array("80" => "08:00", "815" => "08:15", "830" => "08:30", "845" => "08:45", "90" => "09:00", "915" => "09:15", "930" => "09:30", 
		"945" => "09:45", "100" => "10:00", "1015" => "10:15", "1030" => "10:30", "1045" => "10:45", "110" => "11:00", "1115" => "11:15", "1130" => "11:30", 
		"1145" => "11:45", "120" => "12:00", "1215" => "12:15", "1230" => "12:30", "1245" => "12:45", "130" => "13:00", "1315" => "13:15", "1330" => "13:30", 
		"1345" => "13:45", "140" => "14:00", "1415" => "14:15", "1430" => "14:30", "1445" => "14:45", "150" => "15:00", "1515" => "15:15", "1530" => "15:30", 
		"1545" => "15:45", "160" => "16:00", "1615" => "16:15", "1630" => "16:30", "1645" => "16:45", "170" => "17:00", "1715" => "17:15", "1730" => "17:30", 
		"1745" => "17:45", "180" => "18:00", "1815" => "18:15", "1830" => "18:30", "1845" => "18:45", "190" => "19:00", "1915" => "19:15", "1930" => "19:30", "1945" => "19:45");
		$ora = $corrispondenze[$ora].":00";

		$model = new Appuntamento;
		$model->cliente = $cliente;
		$model->trattamento = $trattamento;
		$model->operatore = $operatore;
		$model->data = $anno.'-'.$mese.'-'.$giorno.' '.$ora;
		$model -> save();
		
		$model = Appuntamento::model()->findByPk($id);
		$model -> delete();
		
		echo CJSON::encode("aggiorna");
		
		Yii::app() -> end();
	}

	/**
	 * Validate appuntamento
	 */
	public function actionValidate($giorno, $mese, $anno, $cliente, $ora, $minuti) {

		if ($minuti != '' && $anno != '' && $giorno != '' && $mese != '' && $cliente != '' && $ora != '') {

			if (checkdate($mese, $giorno, $anno)) {
				// Data corretta, controllo se trattamento e cliente vanno bene
				$clienteModel = Cliente::model() -> findByPk($cliente);
				if ($clienteModel != null) {
					echo 'true';
					Yii::app() -> end();
				}
			}
		}
		echo 'false';
		Yii::app() -> end();
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this -> render('view', array('model' => $this -> loadModel($id), ));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$model = new Appuntamento;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$operatori = Operatore::model()->findAll();

		/*if (isset($_POST['Appuntamento'])) {
			$model -> attributes = $_POST['Appuntamento'];
			if ($model -> save())
				$this -> redirect(array('view', 'id' => $model -> id));
		}*/
	
		$this -> renderPartial('create', array('model' => $model, 'operatori'=>$operatori,'modifica'=>false));
	}
	
	/**
	 * Edit a model.
	 */
	public function actionEdit($id) {
		$model = Appuntamento::model() -> findByPk($id);

		$operatori = Operatore::model()->findAll();
		
		if ($model) {
			$clienteModel = Cliente::model()->findByPk($model->cliente);
			$trattamentoModel = Trattamento::model()->findByPk($model->trattamento);
			$this -> renderPartial('edit', array('model' => $model, 'operatori'=>$operatori, 'modifica' => true,'trattamentoModel'=>$trattamentoModel,'clienteModel'=>$clienteModel));
		} else {
			$this -> redirect(array('index'));
		}
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this -> loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Appuntamento'])) {
			$model -> attributes = $_POST['Appuntamento'];
			if ($model -> save())
				$this -> redirect(array('view', 'id' => $model -> id));
		}

		$this -> render('update', array('model' => $model, ));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app() -> request -> isPostRequest) {
			// we only allow deletion via POST request
			$this -> loadModel($id) -> delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this -> redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		} else
			throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Appuntamento');
		$this -> render('index', array('dataProvider' => $dataProvider, ));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Appuntamento('search');
		$model -> unsetAttributes();
		// clear any default values
		if (isset($_GET['Appuntamento']))
			$model -> attributes = $_GET['Appuntamento'];

		$this -> render('admin', array('model' => $model, ));
	}

	public function actionSuggestTrattamento() {

		echo CJSON::encode(array('one', 'two', 'three'));

		Yii::app() -> end();

	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Appuntamento::model() -> findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'appuntamento-form') {
			echo CActiveForm::validate($model);
			Yii::app() -> end();
		}
	}

}
